<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { applyInvoice, getShopSimpleDetail } from '@/api/shop'
import { mailValidator, nameLengthValidator, phoneNumberValidator } from '@/utils/validator'

const applyBaseFormRef = ref(null)
const applyBaseForm = ref({
  merchantName: '',
  merchantId: '',
  type: '1',
})
const applyBaseFormRules = {
  merchantName: [
    { required: true, message: '请填写商家' },
    { message: '商家至少两个字符', validator: nameLengthValidator },
  ],
  type: [{ required: true, message: '请选择抬头类型' }],
}
const applyBusinessFormRef = ref(null)
const applyBusinessForm = ref(({
  taitou: '',
  taxNum: '',
  money: '',
  address: '',
  bankName: '',
  bankAccount: '',
  remark: '',
  phone: '',
  email: '',
}))
const applyBusinessFormRules = {
  taitou: [{ required: true, message: '请输入公司名称' }],
  taxNum: [{ required: true, message: '请输入纳税人识别号' }],
  money: [{ required: true, message: '请输入消费金额' }],
  phone: [{ required: true, message: '请输入联系电话' }, { validator: phoneNumberValidator, message: '手机号格式有误' }],
  email: [{ required: true, message: '请输入邮箱' }, { validator: mailValidator, message: '邮箱格式有误' }],
}
const applyPersonalFormRef = ref(null)
const applyPersonalForm = ref({
  taitou: '',
  money: '',
  remark: '',
  phone: '',
  email: '',
})
const applyPersonalFormRules = {
  taitou: [{ required: true, message: '请输入名称' }],
  money: [{ required: true, message: '请输入消费金额' }],
  phone: [{ required: true, message: '请输入联系电话' }, { validator: phoneNumberValidator, message: '手机号格式有误' }],
  email: [{ required: true, message: '请输入邮箱' }, { validator: mailValidator, message: '邮箱格式有误' }],
}

const confirmVisible = ref(false)

async function onValidate() {
  const { valid: baseValid } = await applyBaseFormRef.value.validate()
  if (!baseValid)
    return

  let nextValid
  if (applyBaseForm.value.type === '1') {
    const { valid } = await applyBusinessFormRef.value.validate()
    nextValid = valid
  }
  else {
    const { valid } = await applyPersonalFormRef.value.validate()
    nextValid = valid
  }

  if (!nextValid)
    return

  confirmVisible.value = true
}

async function onSubmit() {
  try {
    await uni.showLoading({ title: '请稍后' })
    const { success, message } = applyBaseForm.value.type === '1'
      ? await applyInvoice({ ...applyBaseForm.value, ...applyBusinessForm.value })
      : await applyInvoice({ ...applyBaseForm.value, ...applyPersonalForm.value })
    uni.hideLoading()

    if (!success)
      throw new Error(message)
    else
      await uni.redirectTo({ url: '/pages/shop/view/apply-success' })
  }
  catch (e) {
    await uni.showToast({ icon: 'none', title: e.message, duration: 2000 })
  }
}

async function onSetShopName(id) {
  try {
    await uni.showLoading({ title: '请稍后' })
    const { success, message, result } = await getShopSimpleDetail(id)
    uni.hideLoading()

    if (!success)
      throw new Error(message)

    applyBaseForm.value.merchantName = result.name
  }
  catch (e) {
    await uni.showToast({ icon: 'none', title: '获取商家信息失败', duration: 2000 })
  }
}

function goIndex() {
  uni.switchTab({ url: '/pages/index/index' })
}

onLoad(({ q }) => {
  const decodedUrl = decodeURIComponent(q)
  const parts = decodedUrl.split('/')
  const id = parts[parts.length - 1]
  applyBaseForm.value.merchantId = id
  onSetShopName(id)
})
</script>

<template>
  <view class="bg-[#F5F5F5] pb-safe min-h-safe">
    <nut-navbar title="申请开票" custom-color="#000" placeholder fixed>
      <template #left>
        <nut-icon name="home" @click="goIndex" />
      </template>
    </nut-navbar>
    <main class="mt-2">
      <nut-form ref="applyBaseFormRef" :model-value="applyBaseForm" :rules="applyBaseFormRules">
        <nut-form-item label="商家" prop="merchantName">
          <nut-input v-model="applyBaseForm.merchantName" placeholder="请输入商家" disabled type="text" />
        </nut-form-item>
        <nut-form-item label="抬头类型" prop="type">
          <nut-radio-group v-model="applyBaseForm.type" direction="horizontal">
            <nut-radio label="1">
              企业
            </nut-radio>
            <nut-radio label="2">
              个人
            </nut-radio>
          </nut-radio-group>
        </nut-form-item>
      </nut-form>
      <!-- 企业表单 -->
      <nut-form v-if="applyBaseForm.type === '1'" ref="applyBusinessFormRef" :model-value="applyBusinessForm" :rules="applyBusinessFormRules">
        <nut-form-item label="公司名称" prop="taitou">
          <nut-input v-model="applyBusinessForm.taitou" placeholder="请输入名称" type="text" />
        </nut-form-item>
        <nut-form-item label="税号" prop="taxNum">
          <nut-input v-model="applyBusinessForm.taxNum" placeholder="请输入纳税人识别号" type="text" />
        </nut-form-item>
        <nut-form-item label="金额" prop="money">
          <nut-input v-model="applyBusinessForm.money" placeholder="请输入消费金额" type="digit" />
        </nut-form-item>
        <nut-form-item label="详细地址" prop="address">
          <nut-textarea v-model="applyBusinessForm.address" placeholder="请输入地址，不超过40个中文" :autosize="{ maxHeight: 200, minHeight: 50 }" />
        </nut-form-item>
        <nut-form-item label="开户行" prop="bankName">
          <nut-input v-model="applyBusinessForm.bankName" placeholder="请输入开户行" type="text" />
        </nut-form-item>
        <nut-form-item label="银行帐号" prop="bankAccount">
          <nut-input v-model="applyBusinessForm.bankAccount" placeholder="请输入银行帐号" type="text" />
        </nut-form-item>
        <nut-form-item label="备注" prop="remark">
          <nut-input v-model="applyBusinessForm.remark" placeholder="请输入开票原因" type="text" />
        </nut-form-item>
        <nut-form-item label="联系电话" prop="phone">
          <nut-input v-model="applyBusinessForm.phone" placeholder="请输入联系电话" type="tel" />
        </nut-form-item>
        <nut-form-item label="邮箱" prop="email">
          <nut-input v-model="applyBusinessForm.email" placeholder="请输入邮箱" type="text" />
        </nut-form-item>
      </nut-form>
      <!-- 个人表单 -->
      <nut-form v-if="applyBaseForm.type === '2'" ref="applyPersonalFormRef" :model-value="applyPersonalForm" :rules="applyPersonalFormRules">
        <nut-form-item label="个人名称" prop="taitou">
          <nut-input v-model="applyPersonalForm.taitou" placeholder="请输入名称" type="text" />
        </nut-form-item>
        <nut-form-item label="金额" prop="money">
          <nut-input v-model="applyPersonalForm.money" placeholder="请输入消费金额" type="digit" />
        </nut-form-item>
        <nut-form-item label="备注" prop="remark">
          <nut-input v-model="applyPersonalForm.remark" placeholder="请输入开票原因" type="text" />
        </nut-form-item>
        <nut-form-item label="联系电话" prop="phone">
          <nut-input v-model="applyPersonalForm.phone" placeholder="请输入联系电话" type="text" />
        </nut-form-item>
        <nut-form-item label="邮箱" prop="email">
          <nut-input v-model="applyPersonalForm.email" placeholder="请输入邮箱" type="text" />
        </nut-form-item>
      </nut-form>
      <view class="px-3.5">
        <nut-button
          block
          custom-color="linear-gradient(to right, #F89201, #F83600)"
          @click="onValidate"
        >
          确认提交
        </nut-button>
      </view>
      <nut-dialog v-model:visible="confirmVisible" content="确认提交吗?" @ok="onSubmit" />
    </main>
  </view>
</template>
